/* 公共request 方法 */
// const server = 'https://aiteshop.com.cn'; //测试域名api
const server = 'https://uriwin.com'; //正式域名api
const msdjs = require('./md5.js');

function getQueryString(name, url, ture) {
	if (ture) {
		var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
	} else {
		var reg = new RegExp('(^|/?)' + name + '=([^&]*)(&|$)', 'i');
	}
	var r = url.substr(1).match(reg);
	if (r != null) {
		return unescape(r[2]);
	}
	return null;
}

function URLEncode(clearString) {
	var output = '';
	var x = 0;
	clearString = clearString.toString();
	var regex = /(^[a-zA-Z0-9-_.]*)/;
	while (x < clearString.length) {
		var match = regex.exec(clearString.substr(x));
		if (match != null && match.length > 1 && match[1] != '') {
			output += match[1];
			x += match[1].length;
		} else {
			if (clearString.substr(x, 1) == ' ') {
				output += '+';
			} else {
				var charCode = clearString.charCodeAt(x);
				var hexVal = charCode.toString(16);
				output += '%' + (hexVal.length < 2 ? '0' : '') + hexVal.toUpperCase();
			}
			x++;
		}
	}
	return output;
}

const requestUrl = ({
	that,
	url,
	data,
	success,
	asyn = false,
	isFirst = false,
	method = "GET"
}) => {
	let tokenApi = [
		'api.member_order.create'
	]
	data.op = getQueryString("op", url, true) || "";
	data.act = getQueryString("act", url, false) || "";
	if (tokenApi.includes(data.r) && !data.token) {
		uni.showToast({
			title: '未登录，请先登录！',
			icon: 'none',
			duration: 1500
		})
		setTimeout(() => {
			uni.navigateTo({
				url: '/mainA/login/login'
			})
		}, 1500)
		return new Promise((resolve, reject) => {
			reject('login')
		})
	} else {
		let shopping_select = JSON.stringify(uni.getStorageSync("shopping_select"))
		var header = {
			'content-type': 'application/x-www-form-urlencoded',
		}
		//获取当前时间戳
		let timestamp = Date.parse(new Date());
		timestamp = timestamp / 1000;
		data.api_time = timestamp;
		// 不是nvne
		// #ifndef APP-NVUE
		let unionId = uni.getStorageSync("unionId") ? uni.getStorageSync("unionId") : "";
		console.log()
		if (uni.getStorageSync("key")) {

			data.token = uni.getStorageSync("key") ? uni.getStorageSync("key") : "950a233a43fb61f60d1a41831411df00";
			console.log(data.token, "h5")
		}
		if (data.op != "goods_list" && data.act != "goods") {
			data.key = uni.getStorageSync("key") || "";
		}
		// #endif
		// 是nvne
		// #ifdef APP-NVUE
		if (plus.storage.getItem('key')) {
			data.token = plus.storage.getItem('key')
			console.log(data.token, "app")
		}
		let unionId = plus.storage.getItem("unionId") ? plus.storage.getItem("unionId") : "";
		if (data.op != "goods_list" && data.act != "goods") {
			data.key = plus.storage.getItem("key") || "";
		}

		// #endif


		if (data.goods_link) {
			data.goods_link = data.goods_link.replace(/\=/, "%3D")
			data.goods_link = data.goods_link.replace(/\?/g, "%3F")
			data.goods_link = data.goods_link.replace(/\#/g, "%23")
		}
		data.comefrom = "WAP"
		let APIKEY = "AWAP78851ERFG85"
		// #ifdef APP-PLUS
		uni.getSystemInfo({
			success: (res) => {
				if (res.platform == "android") {
					data.comefrom = "Android";
				} else {
					data.comefrom = "IOS";
				}
			}
		})
		APIKEY = "ANHK78451ERFG17"
		// #endif
		// #ifdef H5
		let ua = window.navigator.userAgent.toLowerCase();
		if (ua.match(/MicroMessenger/i) == 'micromessenger') {
			data.comefrom = "WeChat";
			APIKEY = "AWECHAT788NDG85"
		} else {
			data.comefrom = "WAP";
			APIKEY = "AWAP78851ERFG85"
		}
		// #endif
		// #ifdef MP-WEIXIN
		data.comefrom = "APPLET";
		APIKEY = "LET78451EHMG63"
		// #endif



		// 接口签名 
		let api_signMd5 = ksort(data);

		let forinstring = "";

		for (let key in api_signMd5) {
			if (key != "file") {
				forinstring += "&" + key + "=" + encodeURI(api_signMd5[key])
			}
		}

		api_signMd5 = forinstring.replace("&", "") + APIKEY;

		console.log(api_signMd5, 'start')
		api_signMd5 = api_signMd5.replace(/,/g, "%2C")
		api_signMd5 = api_signMd5.replace(/@/g, "%40")
		api_signMd5 = api_signMd5.replace(/\//g, "%2F")
		api_signMd5 = api_signMd5.replace(/:/g, "%3A")
		api_signMd5 = api_signMd5.replace(/\+/g, "%2B")
		api_signMd5 = api_signMd5.replace(/\#/g, "%23")

		console.log(api_signMd5, 'end')
		data.api_sign = msdjs.hexMD5(api_signMd5);
		console.log(data.token, "data.tokendata.tokendata.token")
		data.api_sign = msdjs.hexMD5(api_signMd5).toUpperCase()
		data.api_sign = data.api_sign.toLocaleLowerCase()
		return new Promise(function (resolve, reject) {
			uni.request({
				url: server + url,
				method: method,
				data: data,
				async: asyn,
				header: header,
				success: (res) => {
					//token已失效，您已在其他客户端登录
					if (res.data.message == 'token为空' || res.data.message == 'token已过期，请重新登录' || res.data.error_code == '505' || res.data.error_code == '501') {
						// 先获取路由是否就是登陆页面
						var pages = getCurrentPages();
						var page = pages[pages.length - 1];
						console.log(page.route);
						if (page.route == '/mainA/login/login') {
							console.log("no login")
							return false;
						}
						else {
							console.log("login")
							uni.navigateTo({
								url: '/mainA/login/login'
							})
						}
						return false
					} else if (res.error_code == '1840002') {
						resolve(res.data)
					} else {
						if (isFirst) {
							resolve(res.data)
						} else {
							if (res.data.login == "0") {
								//提示去登陆页面
							} else {
								resolve(res.data)
							}
						}
					}
				},
				fail: function (res) {
					console.log('请求错误', res)
					reject(res.data)
				},
				complete: function (res) {
					if (res.data.error_code == '401' || res.data.error_code == '505') {

						uni.navigateTo({
							url: '/mainA/login/login'
						})
					}

				}
			});
		})
			.catch((res) => { })
	}
}

/* 公共showTotast  loading 方法 */
module.exports = {
	// #ifdef H5
	isWeiXin: isWeiXin,
	// #endif
	request: requestUrl,
	server: server
};
// 环境判断
// #ifdef H5
function isWeiXin() {
	var ua = window.navigator.userAgent.toLowerCase();
	if (ua.match(/MicroMessenger/i) == 'micromessenger' || ua.match(/_SQ_/i) == '_sq_') {
		return true;
	} else {
		return false;
	}
}
// #endif
function ksort(o) {
	let sorted = {},
		keys = Object.keys(o);
	keys.sort();
	keys.forEach((key) => {
		sorted[key] = o[key];
	})
	return sorted;
}
